//
//  VClipVideoVC.m
//  VChatVideoClip
//
//  Created by huangbolun on 2017/10/9.
//  Copyright © 2017年 huangbolun. All rights reserved.
//

#import "VClipVideoVC.h"
#import <AVFoundation/AVFoundation.h>
#import "VClipIndicatorView.h"
#import "VPreviewVC.h"
#import "VVideoClipManger.h"

@interface VClipVideoVC ()<VClipIndicatorViewDelegate>

/**播放器*/
@property(nonatomic, strong) AVPlayer *player;

/**裁剪区间选择器*/
@property(nonatomic, strong) VClipIndicatorView *indicatorView;

/**视频asset对象*/
@property(nonatomic, strong) AVAsset *asset;

/**导航栏*/
@property(nonatomic, strong) UIView *navBar;

/**裁剪左区间*/
@property (nonatomic, assign) CGFloat leftIndicatorValue;

/**裁剪右区间*/
@property (nonatomic, assign) CGFloat rightIndicatorValue;

/**播放进度监听timer*/
@property(nonatomic, strong) NSTimer *avTimer;

@property(nonatomic, strong) UILabel *selecterTimeLabel;

@property (nonatomic, assign) BOOL isAppear;

/**选择视频时长*/
@property (nonatomic, assign) NSInteger selectTimes;

@end

@implementation VClipVideoVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    if (self.asset) {
        [self startTimer];
    }
    self.isAppear = YES;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.player) {
        [self.player play];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [self stopTimer];
    self.isAppear = NO;
    if (self.player) {
        [self.player pause];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    self.rightIndicatorValue = 1;
    //初始化播放器和底部指示器
    [self setupPlayerWithAsset:self.videoAsset];
    [self setupNav];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toForground) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)setupNav{
    //标题栏容器
    UIView *navBar = [UIView new];
    self.navBar = navBar;
    navBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64);
    [self.view addSubview: navBar];
    navBar.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    
    UIView *titleView = [UIView new];
    [navBar addSubview:titleView];
    titleView.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 44);
    
    //标题
    UILabel *titleLabel = [UILabel new];
titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [titleView addSubview:titleLabel];
    [[titleLabel.centerXAnchor constraintEqualToAnchor:titleView.layoutMarginsGuide.centerXAnchor] setActive:YES];
    [[titleLabel.centerYAnchor constraintEqualToAnchor:titleView.layoutMarginsGuide.centerYAnchor] setActive:YES];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"裁剪";
    [titleLabel sizeToFit];
    
    //右边按钮
    UIButton *nextBtn = [UIButton new];
    [titleView addSubview:nextBtn];
    [nextBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [[nextBtn.rightAnchor constraintEqualToAnchor:titleView.rightAnchor constant:-15] setActive:YES];
    [[nextBtn.centerYAnchor constraintEqualToAnchor:titleView.centerYAnchor constant:0] setActive:YES];
    [[nextBtn.widthAnchor constraintEqualToConstant:78] setActive:YES];
    [[nextBtn.heightAnchor constraintEqualToConstant:30] setActive:YES];
    nextBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    nextBtn.clipsToBounds = YES;
    nextBtn.layer.cornerRadius = 15;
    
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    nextBtn.titleLabel.textColor = [UIColor whiteColor];
    [nextBtn setBackgroundColor:[UIColor orangeColor]];
    [nextBtn addTarget:self action:@selector(onNextClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //返回按钮
    UIButton *backBtn = [UIButton new];
    [backBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [titleView addSubview:backBtn];
    [[backBtn.leftAnchor constraintEqualToAnchor:titleView.leftAnchor constant:5] setActive:YES];
    [[backBtn.centerYAnchor constraintEqualToAnchor:titleView.centerYAnchor] setActive:YES];
//    [backBtn setImage:[UIImage imageNamed:@"video_fanhui"] forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    backBtn.titleLabel.textColor = [UIColor whiteColor];
    [backBtn addTarget:self action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];

}

- (void)setupPlayerWithAsset:(PHAsset *)asset{
    [[PHCachingImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if([asset isKindOfClass:[AVAsset class]]){
                self.asset = asset;
                [self playVithAsset:asset];
                [self setupIndicatorWithAsset:asset];
                [self.view bringSubviewToFront:self.navBar];
                
                //开启定时器
                [self startTimer];
            }else{

                NSLog(@"error");
            }
            
            
        }];
    }];
}

- (void)startTimer{
    self.avTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onVideoPlay) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    [self.avTimer invalidate];
    self.avTimer = nil;
}

- (void)playVithAsset:(AVAsset *)asset{
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
    self.player = [[AVPlayer alloc] initWithPlayerItem:item];
    
    AVPlayerLayer *playLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playLayer.frame = [UIScreen mainScreen].bounds;
    [self.view.layer addSublayer:playLayer];
    [self.player play];
    [self.view bringSubviewToFront:self.indicatorView];
}

- (void)setupIndicatorWithAsset:(AVAsset *)asset{
    VClipIndicatorView *indicatorView = [[VClipIndicatorView alloc] initWithFrame:CGRectMake(16, [UIScreen mainScreen].bounds.size.height - 70, [UIScreen mainScreen].bounds.size.width - 32, 65)];
    indicatorView.asset = asset;
    indicatorView.delegate = self;
    self.indicatorView = indicatorView;
    [self.view addSubview:indicatorView];
    
    //设置已选择时间
    UILabel *selecterTimeLabel = [UILabel new];
    self.selecterTimeLabel = selecterTimeLabel;
    [self.view addSubview:selecterTimeLabel];
    selecterTimeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    [[selecterTimeLabel.centerXAnchor constraintEqualToAnchor:self.indicatorView.centerXAnchor constant:0] setActive:YES];
    [[selecterTimeLabel.bottomAnchor constraintEqualToAnchor:self.indicatorView.topAnchor constant:-15] setActive:YES];
    [[selecterTimeLabel.heightAnchor constraintEqualToConstant:30] setActive:YES];
    selecterTimeLabel.layer.cornerRadius = 15;
    selecterTimeLabel.clipsToBounds = YES;
    
    Float64 totalDuring = CMTimeGetSeconds(self.asset.duration);
    selecterTimeLabel.text = [NSString stringWithFormat:@"   已选择%zd秒   ",(NSInteger)totalDuring];
    selecterTimeLabel.textColor = [UIColor whiteColor];
//    [selecterTimeLabel sizeToFit];
    self.selectTimes = (NSInteger)totalDuring;
    
    selecterTimeLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    
    
    
}

#pragma mark - Action
- (void)onNextClick:(UIButton *)sender{
    Float64 totalDuring = CMTimeGetSeconds(self.asset.duration);
    [[VVideoClipManger shareClipManger] clipWithAssert:self.asset Begin:totalDuring * self.leftIndicatorValue end:totalDuring * (self.rightIndicatorValue - self.leftIndicatorValue) compelet:^(NSURL *url) {
        VPreviewVC *vc = [VPreviewVC new];
        vc.videoUrl = url;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)onVideoPlay{
    Float64 totalDuring = CMTimeGetSeconds(self.asset.duration);
    
    Float64 leftTime = totalDuring * self.leftIndicatorValue;
    Float64 rightTime = totalDuring * self.rightIndicatorValue;
    Float64 currentTime = CMTimeGetSeconds(self.player.currentTime);
    if (currentTime >= rightTime) {
        [self.player seekToTime:CMTimeMakeWithSeconds(leftTime, 600)];
        if (1 == self.rightIndicatorValue) {
            [self.player play];
        }
    }
    
    
}


- (void)onBackClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Notification
- (void)toBackground{
    if (self.isAppear) {
        [self.player pause];
    }
}

- (void)toForground{
    if (self.isAppear) {
        [self.player play];
    }
}

#pragma mark - VClipIndicatorViewDelegate
- (void)onIndicatorChanged:(CGFloat)value isLeft:(BOOL)isLeft{
    if (self.avTimer != nil) {
        [self stopTimer];
    }
    
    [self.player pause];
    Float64 totalDuring = CMTimeGetSeconds(self.asset.duration);
    [self.player seekToTime:CMTimeMakeWithSeconds(totalDuring * value, 600)];
    
    NSInteger selectTimes = 0;
    if (isLeft) {
        selectTimes = totalDuring * (self.rightIndicatorValue - value);
    }else{
        selectTimes = totalDuring * (value - self.leftIndicatorValue);
    }
    self.selecterTimeLabel.text = [NSString stringWithFormat:@"   已选择%zd秒   ",selectTimes];
    self.selectTimes = selectTimes;
    
}

- (void)onIndicatorEndWithLeft:(CGFloat)leftValue right:(CGFloat)rightValue{
    if (self.avTimer == nil) {
        [self startTimer];
    }
    
    self.leftIndicatorValue = leftValue;
    self.rightIndicatorValue = rightValue;
    
    Float64 totalDuring = CMTimeGetSeconds(self.asset.duration);
    [self.player seekToTime:CMTimeMakeWithSeconds(totalDuring * leftValue, 600)];
    [self.player play];
    NSLog(@"%lf - %lf",self.leftIndicatorValue,self.rightIndicatorValue);
}


- (void)dealloc{
    NSLog(@"VClipVideoVC - dealloc");
}

@end
